package com.glela.api.upload.qiniu.http;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;

public class HttpStreamRequest
{

	public static String http(String url, String xml) throws MalformedURLException, IOException
	{
		return HttpStreamRequest.http(url, xml, null);
	}

	public static String http(String url, String xml, String encoding) throws MalformedURLException, IOException
	{

		encoding = StringUtils.defaultIfEmpty(encoding, "utf-8");

		InputStream inStream = null;
		URLConnection conn = null;
		String result = null;
		try {
			conn = new URL(url).openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(30 * 1000);
			conn.setReadTimeout(60 * 1000);
			conn.setDefaultUseCaches(false);
			conn.setUseCaches(false);

			byte[] bytes = xml.getBytes(encoding);
//			String outputContent = new String(bytes);

			conn.setRequestProperty("Pragma:", "no-cache");
			conn.setRequestProperty("Cache-Control", "no-cache");
			conn.setRequestProperty("Content-Type", "application/xmlstream");
			conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.connect();

			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encoding);
			out.write(xml);
			out.flush();
			HttpStreamRequest.closeQuietly(out);

			inStream = conn.getInputStream();
			result = HttpStreamRequest.inputStream2String(inStream, encoding);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			HttpStreamRequest.closeQuietly(inStream);
			conn = null;
		}
		return result;
	}

	private static void closeQuietly(Closeable is)
	{
		try {
			if (is != null) {
				is.close();
			}
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private static String inputStream2String(InputStream is, String encoding) throws IOException
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		String result = null;
		try {
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			result = baos.toString(encoding);
		}
		finally {
			HttpStreamRequest.closeQuietly(baos);
		}
		return result;
	}

}
